# -*-coding:utf-8 -*-
"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
@Project : python-base
@File : spider-douyin.py
@Author : 华栖云-罗洋
@Time : 2023/7/13 19:58

"""

import threading
import sys
import shutil
import requests
import jsonpath
import uuid
import os
import time
from get_sec_user_id import get_sec_user_id
from upload_xingzhi import upload
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout

# 定义全局变量
nickname = None
desc = []
video_urls = []


def get_moveurl(num, douyin_domin):
    sec_user_id = get_sec_user_id(douyin_domin)
    url = f"https://www.douyin.com/aweme/v1/web/aweme/post/?aid=6383&sec_user_id={sec_user_id}&count={num}"
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
        "cookie": "bd_ticket_guard_client_web_domain=2; ttwid=1%7CyDZAT7H0ORMWd6XSNMwnoG10q7UlcDcVvby2Jajh-B0%7C1702365412%7C0c8ade5f2162070ad28578de34ae818cd3044b5cd31791fd39332f0f355e60ec; xgplayer_user_id=835376608957; store-region=cn-sc; store-region-src=uid; my_rd=2; LOGIN_STATUS=0; SEARCH_RESULT_LIST_TYPE=%22single%22; UIFID_TEMP=c1122660d8ed0cfe9a6a82cc3a2918814832a6b01c8e88adf78b7472dd4712c45989069a0eb1ca085d375d3baa17fcc26c416e9bef75890bc6746dc0aa2474871deadb850342e4b3a63e0cee7d079460; fpk1=U2FsdGVkX1/GjpXoWnBvqyogtEqoo4BpihCCtcpCKF4vyteMkrjahIB7+VvrNQdx9iSNVLwk6bx9DRgpjGrZFQ==; fpk2=9fea701a627a57d0c458db2e1cb60d62; UIFID=c1122660d8ed0cfe9a6a82cc3a2918814832a6b01c8e88adf78b7472dd4712c45989069a0eb1ca085d375d3baa17fcc2b2153ce6acb4ddc3b56d4079dd46f96acb531d37d76fc74f61f444bceb3ddfd6e92f17687c92ea21b08ee7e40ad8401ddb8f5b175a4a2cca6ea88f6afe2fdd2ed7e2907203299f8da30ac4aa54f13dd827b5deffe3d1990420ba9b640841293d9981ce2e5896ed8281590464c4cbcbf8; hevc_supported=true; passport_csrf_token=5cae36f2bc446a0fa77a2f776cdff0cf; passport_csrf_token_default=5cae36f2bc446a0fa77a2f776cdff0cf; s_v_web_id=verify_m0p17r3f_09c8b8a2_7ea9_8b2f_db2c_f891746d325f; d_ticket=6eeda0ecaa481e8df63ca704a4ecdc1a95d93; n_mh=nirDYsrg8xRIX5a6aWt13rLXmtbujJgPLYFPv82Dq0g; is_staff_user=false; _bd_ticket_crypt_doamin=2; __security_server_data_status=1; live_use_vvc=%22false%22; xgplayer_device_id=26806299947; passport_assist_user=Cj0LzVOuLP9tAt5KAfgVk3Lhtjd9BCfzy8-nDB1ER2YZNiwUvQNHd1Rd9S4uU4X1HtYGwxfUquAgLHk4ff2wGkoKPFzhlc6inZZA2tWNi31rpCk1x-pX8l-ZJxqIIG_2okTWLVKYKcr_p-yfv6fN-tPziesNq3gFm466JccGvRC_8NwNGImv1lQgASIBA4dZWic%3D; sso_uid_tt=56cfb42b8a6a7407d421d44edda707a5; sso_uid_tt_ss=56cfb42b8a6a7407d421d44edda707a5; toutiao_sso_user=a00b86ed04f06f893fab7d6b70f02367; toutiao_sso_user_ss=a00b86ed04f06f893fab7d6b70f02367; sid_ucp_sso_v1=1.0.0-KDRjODViN2M4ZWQ2OTBhN2ZhN2RmZWI1MmI4NDRkNTdmZDg0OTM1MmQKHwij56y_-AIQpeXEtwYY7zEgDDCsj9vZBTgFQPsHSAYaAmxmIiBhMDBiODZlZDA0ZjA2Zjg5M2ZhYjdkNmI3MGYwMjM2Nw; ssid_ucp_sso_v1=1.0.0-KDRjODViN2M4ZWQ2OTBhN2ZhN2RmZWI1MmI4NDRkNTdmZDg0OTM1MmQKHwij56y_-AIQpeXEtwYY7zEgDDCsj9vZBTgFQPsHSAYaAmxmIiBhMDBiODZlZDA0ZjA2Zjg5M2ZhYjdkNmI3MGYwMjM2Nw; uid_tt=5828e2854e577a2584abc2e35d838a6d; uid_tt_ss=5828e2854e577a2584abc2e35d838a6d; sid_tt=88e0bd99a14ebc5dda8cc896ef8ab4b2; sessionid=88e0bd99a14ebc5dda8cc896ef8ab4b2; sessionid_ss=88e0bd99a14ebc5dda8cc896ef8ab4b2; _bd_ticket_crypt_cookie=a246d6aa26969e3e7741d12aae08bebb; SelfTabRedDotControl=%5B%7B%22id%22%3A%227035201648553101349%22%2C%22u%22%3A1240%2C%22c%22%3A1240%7D%5D; douyin.com; xg_device_score=7.90435294117647; device_web_cpu_core=16; device_web_memory_size=8; architecture=amd64; dy_swidth=1707; dy_sheight=1067; csrf_session_id=4ce4e6b606da804de2f895c349ec30e9; FOLLOW_LIVE_POINT_INFO=%22MS4wLjABAAAAv38cQ2JKNyvvxDE26dtA_3yM3PGRL8_-fZ-6lXzsGGM%2F1729526400000%2F0%2F1729482935637%2F0%22; strategyABtestKey=%221729482936.178%22; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Atrue%2C%22volume%22%3A0.5%7D; biz_trace_id=80108edc; sid_guard=88e0bd99a14ebc5dda8cc896ef8ab4b2%7C1729482937%7C5184000%7CFri%2C+20-Dec-2024+03%3A55%3A37+GMT; sid_ucp_v1=1.0.0-KDJiZGE4MzJhOWE3MmI2MmM5ZmYwMDllZDMzYjU4MjQ4ZjVkYTdiZmYKGQij56y_-AIQuaHXuAYY7zEgDDgFQPsHSAQaAmhsIiA4OGUwYmQ5OWExNGViYzVkZGE4Y2M4OTZlZjhhYjRiMg; ssid_ucp_v1=1.0.0-KDJiZGE4MzJhOWE3MmI2MmM5ZmYwMDllZDMzYjU4MjQ4ZjVkYTdiZmYKGQij56y_-AIQuaHXuAYY7zEgDDgFQPsHSAQaAmhsIiA4OGUwYmQ5OWExNGViYzVkZGE4Y2M4OTZlZjhhYjRiMg; stream_player_status_params=%22%7B%5C%22is_auto_play%5C%22%3A0%2C%5C%22is_full_screen%5C%22%3A0%2C%5C%22is_full_webscreen%5C%22%3A0%2C%5C%22is_mute%5C%22%3A1%2C%5C%22is_speed%5C%22%3A1%2C%5C%22is_visible%5C%22%3A0%7D%22; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A1707%2C%5C%22screen_height%5C%22%3A1067%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A16%2C%5C%22device_memory%5C%22%3A8%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A100%7D%22; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCQzh4ZkpRUjJocTNjY3NzL1V0dXNZMU1EdVN1RWFhVFJFOWdOdGxPRXFSN2kzbWcxZXIyalZNTzByUFVlNER2bGg0VEpFRU5RMnVkbFd4S3BlMCtXZjA9IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoyfQ%3D%3D; publish_badge_show_info=%220%2C0%2C0%2C1729482955491%22; download_guide=%221%2F20241021%2F0%22; pwa2=%220%7C0%7C1%7C0%22; odin_tt=9743412e8e3056d2f82da6c50e9a8f5d4eab97fffaca94477adbd9ad12ca62e2afa4bd0d65be8573f0e75713cba345c9; passport_fe_beating_status=false; __ac_nonce=06715e099005f7a757559; __ac_signature=_02B4Z6wo00f01VZXqygAAIDAii40nN8odZFWd6-AADKDb7; IsDouyinActive=true; home_can_add_dy_2_desktop=%220%22"}
    re = requests.get(url=url,headers=header)


    global video_urls
    video_urls = jsonpath.jsonpath(re.json(), "$.aweme_list[*].video.play_addr.url_list[2]")
    print(video_urls)
    # 获取作者的nickname
    global nickname
    nickname = jsonpath.jsonpath(re.json(), "$.aweme_list[0].author.nickname")[0]

    # 获取视频标题：
    global desc
    desc = jsonpath.jsonpath(re.json(), "$.aweme_list[*].desc")
    # print(desc)

    return video_urls,nickname





def download_movie(video_url, filename):
    # 设置请求头
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }

    # 使用 Session 对象来模拟浏览器会话
    session = requests.Session()
    # 访问首页以获取必要的 Cookie
    home_url = "https://www.douyin.com/"
    home_response = session.get(home_url, headers=headers)
    home_response.raise_for_status()


    print(f"正在下载视频 {filename}")

    try:
        # 发送请求
        response = session.get(video_url, headers=headers, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        with open(f"./video/{filename}.mp4", "wb") as file:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    file.write(chunk)
                    file.flush()

        print(f"视频 {filename} 下载完成")

    except requests.exceptions.RequestException as e:
        print(f"下载视频 {filename} 时发生错误: {e}")
    except IOError as e:
        print(f"写入文件 {filename} 时发生错误: {e}")

# def download_movie(video_url, filename):
#     header = {
#         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
#     }
#     print(f"正在下载视频 {filename}")
#     with requests.get(url=video_url, headers=header, stream=True) as response:
#         response.raise_for_status()
#         with open(f"./video/{filename}", "wb") as file:
#             for chunk in response.iter_content(chunk_size=8192):
#                 file.write(chunk)

def download_movies(num, douyin_domin):
    starttime = time.time()
    if not os.path.exists('./video'):
        os.makedirs('./video')
    else:
        shutil.rmtree('./video')
        os.makedirs('./video')

    get_moveurl(num, douyin_domin)

    threads = []
    for video_url, desc_item in zip(video_urls, desc):
        filename = f"{desc_item}.mp4"  # 可以使用 uuid 或其他方式确保唯一性
        t = threading.Thread(target=download_movie, args=(video_url, filename))
        t.start()
        threads.append(t)

    # 等待所有线程完成
    for t in threads:
        t.join()

    endtime = time.time()
    print(f"总共耗时：{endtime - starttime}s")

    # 调用上传至智能媒资的接口
    upload()


class ImageDownloader(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('video Downloader')
        self.setGeometry(300, 300, 300, 300)

        self.content_label = QLabel('请输入你想上传的抖音主页：', self)
        self.content_label.move(20, 20)  # 修改位置

        self.content_textbox = QLineEdit(self)
        self.content_textbox.move(20, 50)  # 修改位置

        self.label = QLabel('你想上传多少条视频：', self)
        self.label.move(20, 80)  # 设置标签的位置

        self.textbox = QLineEdit(self)
        self.textbox.move(20, 110)  # 设置文本框的位置

        self.button = QPushButton('开始上传', self)
        self.button.move(20, 140)  # 设置按钮的位置

        self.button.clicked.connect(self.start_download)

    def start_download(self):
        num = self.textbox.text()
        douyin_domin = self.content_textbox.text()
        download_movies(num, douyin_domin)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 创建窗口对象并显示
    window = ImageDownloader()
    window.show()
    # 运行应用程序主循环
    sys.exit(app.exec_())

#
# if __name__ == '__main__':
#     download_movie()
